package com.cj.wtrails.fragment

import android.graphics.Bitmap
import android.graphics.Bitmap.createBitmap
import android.graphics.BitmapFactory
import android.graphics.Outline
import android.graphics.Rect
import android.os.Handler
import android.view.View
import android.view.ViewOutlineProvider
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.core.view.isVisible
import com.baidu.aip.FaceSDKManager
import com.baidu.aip.ImageFrame
import com.baidu.aip.face.CameraImageSource
import com.baidu.aip.face.FaceCropper
import com.baidu.aip.face.FaceDetectManager
import com.baidu.aip.face.FaceFilter
import com.cj.wtrails.BaseFragment
import com.cj.wtrails.R
import com.cj.wtrails.TvMainActivity
import com.cj.wtrails.bean.DataInfo
import com.cj.wtrails.bean.UserInfo
import com.cj.wtrails.http.RestClient
import com.cj.wtrails.utils.*
import com.google.gson.Gson
import kotlinx.android.synthetic.main.sb_fragment.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 *
 * Created by yi on 2020/7/20.
 */
class SbFragment : BaseFragment() {

    var faceDetectManager: FaceDetectManager? = null
    private val ANGLE = 15.0
    private var mLastTipsTime: Long = 0
    private var mGoodDetect = false
    private var file: File? = null
    private var isFirst = true

    private val handler by lazy {
        Handler()
    }

    override fun getContentLayoutId(): Int {
        return R.layout.sb_fragment
    }

    override fun show() {
    }

    override fun findView() {

    }

    override fun init() {
        setLRAnim(iv_left, true)
        setLRAnim(iv_right, false)
        iv_right.post {
            val margin = CommonUtils.dip2px(activity, 40f)
            val par = RelativeLayout.LayoutParams(iv_right.width - margin, iv_right.height - margin)
            par.addRule(RelativeLayout.CENTER_IN_PARENT)
            cardView.layoutParams = par
        }
        //设置CardView 圆形
        cardView.outlineProvider = object : ViewOutlineProvider() {
            override fun getOutline(view: View, outline: Outline) {
                val dd = view.width.coerceAtLeast(view.height)
                outline.setOval(0, 0, dd, dd)
            }
        }
        cardView.clipToOutline = true

        if (CommonUtils.checkCameraHardware(activity)) {
            initCamera()
        }
    }

    override fun setListener() {
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        isFirst = if (hidden) {
            //pause
            LogUtil.e("sbFragment不可见")
            iv_left.animation?.cancel()
            iv_right.animation?.cancel()
            //faceDetectManager?.stop()
            activity?.supportFragmentManager?.findFragmentByTag("sb")?.let {
                activity?.supportFragmentManager?.beginTransaction()?.remove(it)?.commit()
            }
            (activity as TvMainActivity).sbFragment?.faceDetectManager?.stop()
            (activity as TvMainActivity).sbFragment = null
            true
        } else {
            //resume
            LogUtil.e("SbFragment onResume")
            iv_left.animation?.start()
            iv_right.animation?.start()
            //faceDetectManager?.start()
            false
        }
    }

    private fun setLRAnim(imageView: ImageView, boolean: Boolean) {
        val rotate: RotateAnimation
        if (boolean) {
            rotate = RotateAnimation(
                0f,
                360f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f
            )
        } else {
            rotate = RotateAnimation(
                360f,
                0f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f
            )
        }

        val lin = LinearInterpolator()
        rotate.interpolator = lin
        rotate.duration = 3000 //设置动画持续周期
        rotate.repeatCount = -1 //设置重复次数
        //rotate.fillAfter = true //动画执行完后是否停留在执行完的状态
        rotate.startOffset = 10 //执行前的等待时间
        imageView.animation = rotate
    }

    private fun initCamera() {
        faceDetectManager = FaceDetectManager(activity)
        val cameraImageSource = CameraImageSource(activity)
        cameraImageSource.setPreviewView(preview_view)
        faceDetectManager?.imageSource = cameraImageSource
        faceDetectManager?.start()
        initFaceSDK()
        faceDetectManager?.setOnFaceDetectListener { retCode, infos, frame ->
            LogUtil.e("retcode:$retCode")
            var str = ""
            if (retCode == 0) {
                if (infos != null && infos[0] != null) {
                    val info = infos[0]
                    val headUpDown: Boolean
                    if (info != null) {
                        when {
                            info.headPose[0] >= ANGLE -> {
                                headUpDown = false
                                str = resources.getString(R.string.detect_head_up)
                            }
                            info.headPose[0] <= -ANGLE -> {
                                headUpDown = false
                                str = resources.getString(R.string.detect_head_down)
                            }
                            else -> {
                                headUpDown = true
                            }
                        }
                        val headLeftRight: Boolean
                        when {
                            info.headPose[1] >= ANGLE -> {
                                headLeftRight = false
                                str = resources.getString(R.string.detect_head_left)
                            }
                            info.headPose[1] <= -ANGLE -> {
                                headLeftRight = false
                                str = resources.getString(R.string.detect_head_right)
                            }
                            else -> {
                                headLeftRight = true
                            }
                        }
                        mGoodDetect = headUpDown && headLeftRight
                    }
                }
            } else if (retCode == 1) {
                str = resources.getString(R.string.detect_head_up)
            } else if (retCode == 2) {
                str = resources.getString(R.string.detect_head_down)
            } else if (retCode == 3) {
                str = resources.getString(R.string.detect_head_left)
            } else if (retCode == 4) {
                str = resources.getString(R.string.detect_head_right)
            } else if (retCode == 5) {
                str = resources.getString(R.string.detect_low_light)
            } else if (retCode == 6) {
                str = resources.getString(R.string.detect_face_in)
            } else if (retCode == 7) {
                str = resources.getString(R.string.detect_face_in)
            } else if (retCode == 10) {
                str = resources.getString(R.string.detect_keep)
            } else if (retCode == 11) {
                str = resources.getString(R.string.detect_occ_right_eye)
            } else if (retCode == 12) {
                str = resources.getString(R.string.detect_occ_left_eye)
            } else if (retCode == 13) {
                str = resources.getString(R.string.detect_occ_nose)
            } else if (retCode == 14) {
                str = resources.getString(R.string.detect_occ_mouth)
            } else if (retCode == 15) {
                str = resources.getString(R.string.detect_right_contour)
            } else if (retCode == 16) {
                str = resources.getString(R.string.detect_left_contour)
            } else if (retCode == 17) {
                str = resources.getString(R.string.detect_chin_contour)
            } else if (retCode == -1) {
                str = "非法的参数"
            }
            activity?.runOnUiThread {
                if (System.currentTimeMillis() - mLastTipsTime > 1000) {
                    tv_sb_tips?.text = str
                    mLastTipsTime = System.currentTimeMillis()
                    tv_tips_tips?.text =
                        "GoodDetect:" + mGoodDetect.toString() + "retcode" + retCode
                }
                if (mGoodDetect && retCode == 0) {
                    tv_sb_tips?.text = "识别中..."
                }
            }
            if (infos == null) {
                mGoodDetect = false
            }
        }
        //过滤拿到人脸照片
        faceDetectManager?.setOnTrackListener { it ->
            if (it.meetCriteria() && mGoodDetect) {
                val face: Bitmap = it.cropFace()
                setFaceBitmap(face)
            }
            /*it.trackId?.apply {
                if (isFirst) {
                    isFirst=false
                    val face: Bitmap = it.cropFace()
                    setFaceBitmap(face)
                }
               
            }*/

        }


    }


    private fun setFaceBitmap(face: Bitmap) {
        ImageSaveUtil.saveCameraBitmap(activity, face, "head_tmp.jpg")
        val filePath: String = ImageSaveUtil.loadCameraBitmapPath(activity, "head_tmp.jpg")
        file = File(filePath)
        //压缩裁切图片
        //ImageUtil.resize(face, file, 300, 300)
        file?.apply {
            //上传
            LogUtil.e(this.path)
            upload(this)
        }
    }

    private fun initFaceSDK() {
        FaceSDKManager.getInstance().getFaceTracker(activity).set_min_face_size(200)
        FaceSDKManager.getInstance().getFaceTracker(activity).set_isCheckQuality(true)
        // 该角度为商学，左右，偏头的角度的阀值，大于将无法检测出人脸，为了在1：n的时候分数高，注册尽量使用比较正的人脸，可自行条件角度
        FaceSDKManager.getInstance().getFaceTracker(activity).set_eulur_angle_thr(15, 15, 15)
        FaceSDKManager.getInstance().getFaceTracker(activity).set_isVerifyLive(true)
        FaceSDKManager.getInstance().getFaceTracker(activity).set_notFace_thr(0.2f)
        FaceSDKManager.getInstance().getFaceTracker(activity).set_occlu_thr(0.1f)
        initBrightness()
    }

    //调节屏幕亮度
    private fun initBrightness() {
        val brightness: Int = BrightnessTools.getScreenBrightness(activity)
        if (brightness < 200) {
            BrightnessTools.setBrightness(activity, 200)
        }
    }


    private fun upload(f: File) {
        val body = RequestBody.create(MediaType.parse("multipart/form-data"), f)
        val part = MultipartBody.Part.createFormData("multipartFile", f.name, body)
        RestClient().httpService.general("1", part).enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                LogUtil.e(t.message)
                isFirst=true
            }

            override fun onResponse(
                call: Call<ResponseBody>,
                response: Response<ResponseBody>
            ) {
                response.body()?.string()?.apply {
                    val status = JSONObject(this).optString("status") as String
                    tv_tips_tips?.text = "返回参数：$status"
                    when (status) {
                        //无数据
                        "203" -> {
                            val jsonObject = JSONObject(this)
                            val userInfo =
                                Gson().fromJson(jsonObject.getString("data"), UserInfo::class.java)
                            (activity as? TvMainActivity)?.userInfo = userInfo
                            (activity as? TvMainActivity)?.initNoFragment()
                        }
                        //有数据
                        "200" -> {
                            val jsonObject = JSONObject(this)
                            val dataInfo =
                                Gson().fromJson(jsonObject.getString("data"), DataInfo::class.java)
                            (activity as TvMainActivity).dataInfo = dataInfo
                            (activity as TvMainActivity).initDataFragment()
                        }
                        //已注册
                        "201" -> {
                            val jsonObject = JSONObject(this)
                            val qrcode = jsonObject.getJSONObject("data").getString("qrcode")
                            val bitmap = stringToBitmap(qrcode)
                            (activity as TvMainActivity).qrImage = bitmap
                            (activity as TvMainActivity).initSuccessFragment()
                        }
                        //202照片不合格,405重复提交
                        else -> {
                            activity?.runOnUiThread {
                                tv_sb_tips.text = JSONObject(this).getString("data")
                            }
                            isFirst=true
                        }
                    }
                }

            }

        })
    }
}